package luanvan.app.foodnote.library;

import java.util.HashMap;

import luanvan.app.foodnote.LocationActivity;
import luanvan.app.foodnote.LoginActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class SessionManager {

	// Shared Preferences
	SharedPreferences pref;
	
	// Editor for Shared preferences
	Editor editor;
	
	// Context
	Context _context;
	
	// Shared pref mode
	int PRIVATE_MODE = 0;
	
	// Sharedpref file name
	private static final String PREF_NAME = "FoodNotePref";
	
	// All Shared Preferences Keys
	private static final String IS_LOGIN = "IsLoggedIn";
	
	// User name
	public static final String KEY_NAME = "name";
	
	// Email address
	public static final String KEY_EMAIL = "email";
	
	// UID
	public static final String KEY_UID = "uid";
	
	@SuppressLint("CommitPrefEdits")
	public SessionManager(Context context){
		this._context = context;
		pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
		editor = pref.edit();
	}
	
	// Create login session
	public void createLoginSession(String name, String email, String uid){
		// Storing login value as TRUE
		editor.putBoolean(IS_LOGIN, true);
		
		// Storing name in pref
		editor.putString(KEY_NAME, name);
		
		// Storing email in pref
		editor.putString(KEY_EMAIL, email);
		
		// Storing uid
		editor.putString(KEY_UID, uid);
		
		// Commit changes
		editor.commit();
	}
	
	// Get stored session data
	public HashMap<String, String> getUserDetails(){
		HashMap<String, String> user = new HashMap<String, String>();
		
		// user name
		user.put(KEY_NAME, pref.getString(KEY_NAME, null));
		
		// user email id
		user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
		
		// uid
		user.put(KEY_UID, pref.getString(KEY_UID, null));
		
		return user;
	}
	
	// Check login
	public void checkLogin(){
		if(!this.isLoggedIn()){
			// user is not logged in redirect to Login Activity
			Intent i = new Intent(_context, LocationActivity.class);
			
			// Closing all the Activities
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			
			// Add new Flag to start new Activity
			i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			
			_context.startActivity(i);
			
		}
	}

	public boolean isLoggedIn() {
		// TODO Auto-generated method stub
		return pref.getBoolean(IS_LOGIN, false);
	}
	
	// Clear session details
	public void logoutUser(){
		// Clearing all data from Shared Preferences
		editor.clear();
		editor.commit();
		
		// After logout redirect user to Login Activity
		Intent i = new Intent(_context, LoginActivity.class);
		// Closing all the Activities
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
 
        // Add new Flag to start new Activity
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 
        // Staring Login Activity
        _context.startActivity(i);
	}
}
